package com.gec.mall.security.filter;

import com.gec.mall.security.utils.JwtTokenUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author: li
 * @Date: 2023/2/17
 * @PACKAGE_NAME:com.gec.security.filter
 * @Project_Name:Javademo
 * @VERSION: 1.0.0
 */
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    //拦截过滤的主方法： 判断用户是否有token，token的有效性
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中token，名称：authorization（固定名）
        String tokenHeader = request.getHeader("authorization");
        System.out.println("tokenHeader = " + tokenHeader);

        //判断token的合法性
        if ( tokenHeader!=null && tokenHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)){
            //token合法性判断，成功判断后，要返回合法性的用户密码的token,并且重新登记回security的上下文
            UsernamePasswordAuthenticationToken token = getAuthentication(tokenHeader);
            SecurityContextHolder.getContext().setAuthentication(token);
        }
        filterChain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
        //去掉token前缀
        String replace = tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX, "");
        //有效性的规则：只需要获取账号，不为null
        String username = JwtTokenUtil.getProperties(replace);
        if (username!=null){
            return new UsernamePasswordAuthenticationToken(username, null,new ArrayList<>());
        }
        return null;
    }
}
